import { IGetAuthorityResponseData } from "@/api/authority/types/authority"
import { useUserStoreHook } from "@/store/modules/user"
import dayjs from "dayjs"
import { ElMessage, UploadRawFile } from "element-plus"

/** 格式化时间 */
export const formatDateTime = (time: string | number | Date) => {
  if (!time) {
    return "N/A"
  }
  const date = new Date(time)
  return dayjs(date).format("YYYY-MM-DD HH:mm:ss")
}

/** 将全局 CSS 变量导入 JS 中使用 */
export const getCssVariableValue = (cssVariableName: string) => {
  let cssVariableValue = ""
  try {
    // 没有拿到值时，会返回空串
    cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
  } catch (error) {
    console.error(error)
  }
  return cssVariableValue
}

/**
 * 消息提示
 * @param type
 * @param message
 */
export const showPromptMessage = (type: "success" | "warning" | "info" | "error", message: string) => {
  ElMessage({
    type,
    message,
    grouping: true
  })
}

/**
 * 打开文件下载
 * @param blobData 二进制数据
 * @param fileName 文件名
 */
export const openDownload = (blobData: Blob, fileName: string) => {
  const blob = new Blob([blobData])
  const downloadElement = document.createElement("a")
  const href = window.URL.createObjectURL(blob)
  downloadElement.href = href
  downloadElement.download = fileName
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
  window.URL.revokeObjectURL(href)
}

export const downloadByUrl = (url: string, fileName: string) => {
  const downloadElement = document.createElement("a")
  downloadElement.href = url
  downloadElement.download = fileName
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
}

/**
 * 在新标签打开预览
 * @param url 预览地址
 */
export const previewOnNewTab = (url: string) => {
  const downloadElement = document.createElement("a")
  downloadElement.href = url
  downloadElement.target = "_blank"
  document.body.appendChild(downloadElement)
  downloadElement.click()
  document.body.removeChild(downloadElement)
}

/**
 * 判断是否是图片
 * @param type 文件类型
 * @returns {Boolean}
 */
export const isImage = (type: string | undefined) => {
  if (!type) return false
  const reg = /jpg|png|jpeg/
  return reg.test(type)
}
/**
 * 判断是否是excel文件
 * @param type 文件类型
 * @returns {Boolean}
 */
export const isExcel = (type: string | undefined) => {
  if (!type) return false
  const reg = /excel|spreadsheetml\.sheet/
  return reg.test(type)
}

/**
 * 获取图片尺寸
 * @param file
 * @returns
 */
export const getImageSize = (file: UploadRawFile | undefined): Promise<{ width: number; height: number }> => {
  return new Promise((resolve) => {
    if (!file) return resolve({ width: 0, height: 0 })
    const _URL = window.URL || window.webkitURL
    const img = new Image()
    img.src = _URL.createObjectURL(file)
    // 如果存在浏览器缓存中
    if (img.complete) {
      console.log({ width: img.width, height: img.height })
      resolve({ width: img.width, height: img.height })
    } else {
      img.onload = function () {
        resolve({ width: img.width, height: img.height })
      }
    }
  })
}

export const getCheckedKeys = (authList: any[], key = "id", checkedKeys: number[] = []) => {
  authList.forEach((auth) => {
    console.log(auth, key)
    if (auth.isGranted === 1) {
      auth[key] && checkedKeys.push(auth[key])
    }
    if (auth.children && auth.children.length > 0) {
      getCheckedKeys(auth.children, key, checkedKeys)
    }
  })
  return checkedKeys
}

export const getExpandedKeys = (authList: IGetAuthorityResponseData[]) => {
  const expandedKeys: number[] = []
  authList.forEach((auth) => {
    if (auth.children && auth.children.length > 0) {
      //查找子元素是否有授权
      const hasIndex = auth.children.findIndex((c) => c.isGranted === 1)
      if (hasIndex >= 0 && auth.id) expandedKeys.push(auth.id)
    }
  })
  return expandedKeys
}

/**
 * 是否具有某个权限
 * @param authority
 * @returns
 */
export const hasAnthority = (authority: string | undefined) => {
  if (!authority) return false
  const userStore = useUserStoreHook()
  return userStore.authorities.indexOf(authority) >= 0
}

export const isSameOrIncludes = (p: any[], c: any[]) => {
  const set = new Set([...p, ...c])

  if (p.length < c.length || set.size > p.length) {
    return false
  } else return true
}

/**
 * 获取文件后缀名
 * @param name
 * @returns
 */
export const getExtName = (name: string) => {
  if (!name) return ""
  const flag = name.lastIndexOf(".")
  return name.slice(flag)
}
